#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static void usage(const std::string &proc)
{
    std::cout << "usage\n"
              << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        usage(argv[0]);
        return 3;
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(std::stoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t len = sizeof(server);

    while (true)
    {
        int cnt = 5;
        bool isreconnect = false;
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "create sockfd failed" << std::endl;
            return 1;
        }
        do
        {
            int n = connect(sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect sockfd failed.... . reconect: " << cnt << std::endl;
                // close(sockfd);
                sleep(2);
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offline ..." << std::endl;
            break;
        }

        std::string message;
        // 长连接
        // while (true)
        // {
            std::cout << "Please Enter# ";
            std::getline(std::cin, message);
            int n = write(sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                // isreconnect = true;
                std::cerr << "write error ..." << std::endl;
                continue;
                // break;
            }

            char inbuffer[64];
            n = read(sockfd, inbuffer, 64);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            else{
                // break;
            }
        // }
        close(sockfd);
    }

    return 0;
}